package com.atguigu.myzhxy.controller;

import com.atguigu.myzhxy.pojo.Admin;
import com.atguigu.myzhxy.pojo.LoginForm;
import com.atguigu.myzhxy.pojo.Student;
import com.atguigu.myzhxy.pojo.Teacher;
import com.atguigu.myzhxy.service.AdminService;
import com.atguigu.myzhxy.service.StudentService;
import com.atguigu.myzhxy.service.TeacherService;
import com.atguigu.myzhxy.util.CreateVerifiCodeImage;
import com.atguigu.myzhxy.util.JwtHelper;
import com.atguigu.myzhxy.util.Result;
import com.atguigu.myzhxy.util.ResultCodeEnum;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response) {
        //获取验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取图片上的验证码文本
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        //将验证码文本放入session域，为验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode", verifiCode);
        //将验证码图片响应给浏览器
        try {
            ImageIO.write(verifiCodeImage, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
        //验证码校验
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode");
        String loginVerifiCode = loginForm.getVerifiCode();
        if ("".equals(sessionVerifiCode) || null == sessionVerifiCode) {
            return Result.fail().message("验证码失效，请刷新后重试！");
        }
        if (!sessionVerifiCode.equals(loginVerifiCode)) {
            return Result.fail().message("验证码有误，请重新填写验证码！");
        }
        //验证码校验完后移除
        session.removeAttribute("verifiCode");

        //存放data的对象
        Map<String, Object> map = new LinkedHashMap<>();
        //分用户类型校验登录信息
        switch (loginForm.getUserType()) {
            case 1:
                //调用service层查找符合的对象
                Admin admin = adminService.login(loginForm);
                if (null != admin) {
                    //生成token，按照格式返回前台
                    String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                    map.put("token", token);
                    return Result.ok(map);
                } else {
                    return Result.fail().message("用户名密码有误");
                }
            case 2:
                //调用service层查找符合的对象
                Student student = studentService.login(loginForm);
                if (null != student) {
                    //生成token，按照格式返回前台
                    String token = JwtHelper.createToken(student.getId().longValue(), 2);
                    map.put("token", token);
                    return Result.ok(map);
                } else {
                    return Result.fail().message("用户名密码有误");
                }

            case 3:
                //调用service层查找符合的对象
                Teacher teacher = teacherService.login(loginForm);
                if (null != teacher) {
                    //生成token，按照格式返回前台
                    String token = JwtHelper.createToken(teacher.getId().longValue(), 3);
                    map.put("token", token);
                    return Result.ok(map);
                } else {
                    return Result.fail().message("用户名密码有误");
                }
            default:
                return Result.fail().message("无此类型用户！");
        }
    }

    @GetMapping("/getInfo")
    public Result getInfo(@RequestHeader("token") String token) {
        //判断token是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //解析出用户id和type
        Long userId = JwtHelper.getUserId(token);
        Integer type = JwtHelper.getUserType(token);

        //准备一个临时存储对象的map集合
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        //根据userId和type查询具体信息
        switch (type) {
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("userTpye",1);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getById(userId);
                map.put("userTpye",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getById(userId);
                map.put("userTpye",3);
                map.put("user",teacher);
                break;
        }
        return Result.ok(map).message("成功");
    }

}
